from uuid import uuid4
import json
import os
from datetime import datetime
from django.db.models import Q

from rest_framework import serializers

from .models import *
from apps import redis_client
from apps.products.models import ProductModel
from apps.order.models import OrderModel
from apps.devices.models import DevicesModel
from util.exception import ValidationError
from util.svn_tool import SvnPathTool, SvnTool
from util.smt_tool import SmtTool
from django.conf import settings


class publishCreateSerializer(serializers.ModelSerializer):
    items = serializers.DictField(allow_null=False)

    class Meta:
        model = PublishModel
        fields = ["items"]

    "OrderedDict([('items', {'data': [{'svn': ['硬件/', 'TAC13/', '测试资料V1.0.rar'], 'hard': '1', 'file_type': 'hardware', 'product': ['CPTAC11000'], 'description': '11111'}]})])"

    def create(self, data):
        data = data.get("items")
        data = data.get("data")[0]
        file_type = data.get("file_type")
        file_type = int(file_type)
        has_hardware = False
        has_toolware = False
        has_parameterware = False
        has_software = False
        if file_type == 1:
            has_hardware = True
        elif file_type == 2:
            has_toolware = True
        elif file_type == 3:
            has_parameterware = True
        elif file_type == 4:
            has_software = True
        else:
            raise ValidationError(20001)
        if has_hardware or has_toolware or has_parameterware or has_software:
            publish_id = self.__create_publish(data, has_hardware, has_toolware, has_software, has_parameterware)
            content = self.__create_publish_detial(publish_id, settings.HARDWARE, data)
            file = "publish.text"
            with open(file, "w") as f:
                f.write(content)
            file_path = "{}/{}".format(os.getcwd(), file)
            emials = EmailModel.objects.filter(is_delete=False).filter(is_active=True).all()
            emial_addrs = []
            for em in emials:
                emial_addrs.append(em.email_name)
            SmtTool(emial_addrs).send_email(file_path)
        else:
            raise ValidationError(20003)

    def __create_publish(self, data, has_hardware, has_toolware, has_software, has_parameterware):
        id = str(uuid4()).replace("-", "")
        description = data.get("description")
        product_number = "".join(data.get("product"))
        file_name = data.get("svn")[-1]
        if has_hardware:
            file_type = 1
        elif has_toolware:
            file_type = 2
        elif has_software:
            file_type = 3
        else:
            file_type = 4
        data = {
            "id": id,
            "product_number": product_number,
            "description": description,
            "file_type": file_type,
            "file_name": file_name
        }
        PublishModel.objects.create(**data)
        return id

    def __create_publish_detial(self, publish_id, file_type, data):
        content = ""
        product_numbers = data.get("product")
        file_path = "".join(data.get("svn"))
        file_name = data.get("svn")[-1]
        file_name = file_name.replace("/", "")
        hard_version = data.get("hard")
        version = self.__get_version(file_path)
        if hard_version:
            content = content + "文件名称:{}, 硬件版本:{}, 版本:{}, 产品品号:{}\n".format(file_name, hard_version, version,
                                                                            ",".join(product_numbers))
        else:
            content = content + "文件名称:{}, 版本:{}, 产品品号:{}\n".format(file_name, version, ",".join(product_numbers))
        for pro in product_numbers:
            description = self.__get_msg(file_path)
            data = {
                "id": str(uuid4()).replace("-", ""),
                "publish_id": publish_id,
                "product_number": pro,
                "file_name": file_name,
                "file_path": file_path,
                "file_type": file_type,
                "hard_version": hard_version,
                "description":description,
                "version": version,
            }
            PublishDetialModel.objects.create(**data)
            if file_type == settings.TOOLWARE:
                self.__create_tool_product(version, product_numbers, file_name, file_path)
        return content

    def __create_tool_product(self, version, product_numbers, file_name, file_path):
        for pro in product_numbers:
            product_number = pro
            model = ToolProductModel.objects.filter(product_number=product_number).filter(file_name=file_name).filter(
                version=version).first()
            if not model:
                data = {
                    "id": str(uuid4()).replace("-", ""),
                    "product_number": pro,
                    "file_name": file_name,
                    "file_path": file_path,
                    "version": version
                }
                ToolProductModel.objects.create(**data)

    def __get_version(self, file_path):
        svn_tool = SvnPathTool()
        version_name = svn_tool.get_log(file_path)
        return version_name

    def __get_msg(self, file_path):
        svn_tool = SvnPathTool()
        msg = svn_tool.get_commit_msg(file_path)
        return msg

    def __check(self, datas):
        if datas:
            for data in datas:
                for d, v in data.items():
                    if not v:
                        return False
                return True
        else:
            return False


class VersionDetialSerializer(serializers.ModelSerializer):
    file_name = serializers.CharField(max_length=50, allow_null=False, allow_blank=False)

    def search(self, data):
        file_name = data.get("file_name")
        version = self.__get_version(file_name)
        return [{"file_name": file_name, "version": version}]

    def __get_version(self, file_path):
        svn_tool = SvnPathTool()
        version_name = svn_tool.get_log(file_path)
        return version_name

    class Meta:
        model = PublishModel
        fields = ["file_name"]


class PublishListSerializer(serializers.ModelSerializer):
    class Meta:
        model = PublishModel
        fields = ["id", "publish_date", "product_number", "description", "file_type", "file_name"]


class PublishDetialListSerializer(serializers.ModelSerializer):
    class Meta:
        model = PublishDetialModel
        fields = ["publish_id", "product_number", "file_name", "file_type", "hard_version", "version", "description"]


class ToolSerializer(serializers.ModelSerializer):
    class Meta:
        model = ToolProductModel
        fields = ["file_name", "product_number"]


class VersionSerializer(serializers.ModelSerializer):
    class Meta:
        model = ToolProductModel
        fields = ["file_name", "product_number", "version", "file_path"]


class VersionDownSerializer(serializers.ModelSerializer):
    file_path = serializers.CharField(max_length=50, allow_null=False, allow_blank=False)
    version = serializers.CharField(max_length=50, allow_null=False, allow_blank=False)

    def get_file(self, data):
        file_path = data.get("file_path")
        version = data.get("version")
        svn_tool = SvnTool(file_path, version)
        has_file = svn_tool.get_origin_file()
        return file_path, has_file

    def __get_version(self, file_path):
        svn_tool = SvnPathTool()
        version_name = svn_tool.get_log(file_path)
        return version_name

    class Meta:
        model = ToolProductModel
        fields = ["file_path", "version"]


class EmailListSerializer(serializers.ModelSerializer):
    class Meta:
        model = EmailModel
        fields = ["id", "email_name", "is_delete", "is_active"]


class EmailCreateSerializerList(serializers.ModelSerializer):
    email_name = serializers.CharField(max_length=20, allow_null=False, allow_blank=False)

    class Meta:
        model = EmailModel
        fields = ["email_name"]

    def create(self, validated_data):
        data = {
            "id": str(uuid4()).replace("-", ""),
            "email_name": validated_data.get("email_name"),
        }
        EmailModel.objects.create(**data)


class EmailserializerUpdate(serializers.ModelSerializer):
    id = serializers.CharField(max_length=32, allow_null=False)
    is_active = serializers.BooleanField(allow_null=True, default=True)
    is_delete = serializers.BooleanField(allow_null=True, default=False)

    class Meta:
        model = EmailModel
        fields = ["id", "is_delete", "is_active"]

    def validate(self, attrs):
        id = attrs.get("id")
        email = EmailModel.objects.filter(id=id, is_delete=False).first()
        if not email:
            raise ValidationError(10002)
        new_attrs = {}
        for key, value in attrs.items():
            if value is not None:
                new_attrs[key] = value
        return new_attrs

    def update_user(self, data):
        EmailModel.objects.filter(id=data["id"]).update(**data)
